package com.atguigu.tingshu.account.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.Tocharge;
import com.atguigu.tingshu.vo.account.RechargeInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {

    @Autowired
    private RechargeInfoMapper rechargeInfoMapper;
    @Autowired
    private UserAccountMapper userAccountMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void submitRecharge(Tocharge tocharge) {

        RechargeInfo rechargeInfo = new RechargeInfo();
        rechargeInfo.setRechargeAmount(tocharge.getAmount());
        rechargeInfo.setPayWay(tocharge.getPayWay());
        // 1.生成订单编号
        rechargeInfo.setOrderNo(IdWorker.getIdStr());
        // 2.设置用户ID
        Long userId = AuthContextHolder.getUserId();
        rechargeInfo.setUserId(userId);
        // 3.设置充值状态为未支付
        rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
        // 4.保存订单信息
        rechargeInfoMapper.insert(rechargeInfo);
        // 5. 修改账户余额 需要的参数  用户id 和 金额
        userAccountMapper.updateAmount(userId, rechargeInfo.getRechargeAmount());

    }
}
